import sys, math, random
from PyQt5.QtWidgets import (QApplication, QGraphicsView, QGraphicsScene,
                             QGraphicsRectItem, QGraphicsEllipseItem,
                             QVBoxLayout, QWidget, QPushButton)
from PyQt5.QtCore import Qt, QTimer, QPointF
from PyQt5.QtGui import QBrush, QColor, QPen
from PyQt5.QtGui import QPainter 

class View(QGraphicsView):
    def __init__(self):
        super().__init__()
        # 1. 建舞台
        self.scene = QGraphicsScene(self)
        self.scene.setSceneRect(-200, -200, 400, 400)  # 逻辑坐标系
        self.setScene(self.scene)

        # 2. 放一些基础图元
        self._populate()

        # 3. 视图美化
        self.setDragMode(QGraphicsView.ScrollHandDrag)  # 空格+鼠标拖曳
        self.setRenderHints(QPainter.Antialiasing)

        # 4. 缩放支持（滚轮）
        self.scale(1.2, 1.2)

    def _populate(self):
        # 矩形
        rect = QGraphicsRectItem(0, 0, 60, 40)
        rect.setPos(-100, -100)
        rect.setBrush(QBrush(QColor("#f5b642")))
        rect.setFlag(QGraphicsRectItem.ItemIsMovable)
        rect.setFlag(QGraphicsRectItem.ItemIsSelectable)
        self.scene.addItem(rect)

        # 圆
        for _ in range(15):
            x, y = random.randint(-150, 150), random.randint(-150, 150)
            rad = random.randint(5, 20)
            ellipse = QGraphicsEllipseItem(0, 0, rad*2, rad*2)
            ellipse.setPos(x, y)
            ellipse.setBrush(QBrush(QColor(random.choice(["#5e81ac","#88c0d0","#d08770"]))))
            ellipse.setPen(QPen(Qt.NoPen))
            ellipse.setFlag(QGraphicsEllipseItem.ItemIsMovable)
            self.scene.addItem(ellipse)

        # 文字（可选）
        # text = self.scene.addText("PyQt GraphicsView", QFont("Arial", 16))
        # text.setDefaultTextColor(QColor("#2e3440"))
        # text.setPos(-80, 80)

    def wheelEvent(self, event):
        # 滚轮缩放
        factor = 1.15 if event.angleDelta().y() > 0 else 1/1.15
        self.scale(factor, factor)

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.view = View()
        self.btn = QPushButton("旋转 45°")
        self.btn.clicked.connect(self.rotate_scene)

        lay = QVBoxLayout(self)
        lay.addWidget(self.view)
        lay.addWidget(self.btn)

    def rotate_scene(self):
        # 让场景绕原点旋转（也可对单个 item 旋转）
        self.view.rotate(45)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Demo()
    win.setWindowTitle("PyQt GraphicsView 骨架")
    win.resize(600, 500)
    win.show()
    sys.exit(app.exec_())